package multiThreadSafe3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * # @File  : TicketSale.java
 * # @Author: Lomo
 * # @Site  : lomo.space
 * # @Date  : 2021-09-12
 * # @Desc  : 方式3：使用 lock 对象(Lock 锁)保障多线程安全
 * 场景：多线程卖票
 */
public class TicketSale {
    public static void main(String[] args) {
        RunnableImpl runnable = new RunnableImpl();

        for (int i = 1; i < 5; i ++) {
            Thread thread = new Thread(runnable);
            thread.start();
        }
    }
}

class RunnableImpl implements Runnable {
    private int ticket = 1000;

    private Lock l = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            l.lock();  // 在可能会出现安全问题的代码前调用 lock 方法获取锁
            if (ticket > 0) {
                try {
                    Thread.sleep(20);
                    System.out.println(Thread.currentThread().getName()+ "-->正在售卖第" + ticket + "张票");
                    ticket --;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    l.unlock(); // 最后释放锁! 无论程序是否异常。
                }
            }
        }
    }
}
